package qingxin.servlet.admin.feedback;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import qingxin.dao.FeedbackDAO;
import qingxin.dao.UserDAO;
import qingxin.factory.DAOFactory;
import qingxin.servlet.admin.AdminServlet;
import qingxin.vo.Feedback;

@WebServlet("/admin/feedback/getAll")
public class GetAllFeedbackServlet extends AdminServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private FeedbackDAO feedbackDAO;
	private UserDAO userDAO;
	
	public GetAllFeedbackServlet(){
		super();
		feedbackDAO = DAOFactory.getFeedbackDAO();
		userDAO = DAOFactory.getUserDAO();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html; charset=utf-8");
    	response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		if(!verification(request)){
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			return;
		}
		
		try{
			String limitS = request.getParameter("limit");
			int limit = (limitS == null) ? 20 : Integer.parseInt(limitS);
			String startS = request.getParameter("start");
			int start = (startS == null) ? Integer.MAX_VALUE : Integer.parseInt(startS);
			
			Feedback[] feedbacks = feedbackDAO.getAll(limit, start);
			JSONObject jsonResult = new JSONObject();
			JSONArray jsonFeedbacks = new JSONArray();
			for(Feedback feedback : feedbacks){
				JSONObject jsonFeedback = new JSONObject();
				jsonFeedback.put("id", feedback.getTipID());
				jsonFeedback.put("content", feedback.getContent());
				jsonFeedback.put("datetime", feedback.getDate());
				int uid = feedback.getUserID();
				if(uid != 0){
					jsonFeedback.put("username",userDAO.getByID(uid).getUserName());
				}
				jsonFeedbacks.put(jsonFeedback);
			}
			jsonResult.put("feedbacks", jsonFeedbacks);
			
			writer.println(jsonResult.toString());
			response.setStatus(HttpServletResponse.SC_OK);
		}
		catch(Exception e){
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			writer.println("{\"msg\":\"wrong\"}");
		}
		finally{
			writer.flush();
			writer.close();
		}
	}
}
